import React,{Component} from 'react';
import { Route, IndexRoute,browserHistory,Router,Redirect } from 'react-router';

import dataStore from './stores/dataStore'

// Components
import Home from './Home'
import About from './About'
import Nav from './Nav'

import {fetchData} from './stores/storeInServer'

const checkWindow = () =>{

  var isBrowser = false;
  console.log(typeof window);
  console.log(typeof window !== 'undefined');

  if(typeof window !== 'undefined'){
    isBrowser = true;
  }

  return isBrowser;

}

const enterRoute=(nextState,replace,callback)=>{

  console.log('nextState: ', nextState);

  if(checkWindow()){

    if(window._isReadData){

      console.log('window._initState: ', window._initState);
      
      dataStore.initData(window._initState);
      window._isReadData = false;
      callback();

    }else{

      fetchData(nextState.location).then(data=>{
        callback();
      })

    }

  }

  else{

    callback();

  }

}

const RouteApp = () =>{


  return(
    <Router history={browserHistory}>
        <Route path="/app" component={Nav}>
          <Route path="home" onEnter={enterRoute} component={Home} />
          <Route path="about" onEnter={enterRoute} component={About} />
        </Route>
        <Redirect from="/" to="/app/home" />
      </Router>
  )

}

export default RouteApp;